// 页面滚动辅助函数
export async function autoScrollInContainer(containerSelector, options = {}) {
  const {
    scrollStep = 300,  // 每次滚动的像素
    delay = 300,       // 滚动间隔时间
    bufferTime = 800   // 到底后等待时间
  } = options;

  if (window.__scrollRunning) {
    console.warn("⏹️ 自动滚动已在运行中");
    return false;
  }

  window.__scrollRunning = true;

  return new Promise((resolve, reject) => {
    const container = document.querySelector(containerSelector);
    if (!container) {
      console.error(`❌ 没找到滚动容器: ${containerSelector}`);
      window.__scrollRunning = false;
      reject(new Error(`找不到容器: ${containerSelector}`));
      return;
    }

    let currentScrollTop = 0;
    let lastScrollTop = -1;
    let retryCount = 0;
    const maxRetries = 3;

    function scrollDown() {
      currentScrollTop = container.scrollTop;
      const maxScrollTop = container.scrollHeight - container.clientHeight;

      // 检查是否到达底部或滚动位置没有变化
      if (currentScrollTop >= maxScrollTop || currentScrollTop === lastScrollTop) {
        retryCount++;
        
        if (retryCount >= maxRetries) {
          console.log("✅ 已滚动到底，准备返回顶部");
          setTimeout(() => {
            container.scrollTo({ top: 0, behavior: 'smooth' });
            console.log("⬆️ 已返回顶部");
            window.__scrollRunning = false;
            resolve(true);
          }, bufferTime);
          return;
        }
      }

      lastScrollTop = currentScrollTop;
      container.scrollBy(0, scrollStep);
      setTimeout(scrollDown, delay);
    }

    scrollDown();
  });
}

/**
 * 滚动容器到指定元素位置
 * @param {string} containerSelector - 滚动容器的选择器
 * @param {HTMLElement} targetElement - 目标元素
 * @param {Object} options - 配置选项
 * @param {number} options.offset - 顶部偏移量，默认100
 * @param {number} options.delay - 滚动后等待时间，默认500
 * @returns {Promise<boolean>} - 返回滚动是否成功
 */
export async function scrollToElement(containerSelector, targetElement, options = {}) {
  const {
    offset = 100,  // 顶部偏移量
    delay = 500    // 滚动后等待时间
  } = options;

  return new Promise((resolve, reject) => {
    const container = document.querySelector(containerSelector);
    if (!container) {
      console.error(`❌ 没找到滚动容器: ${containerSelector}`);
      reject(new Error(`找不到容器: ${containerSelector}`));
      return;
    }

    if (!targetElement) {
      console.error('❌ 目标元素不存在');
      reject(new Error('目标元素不存在'));
      return;
    }

    try {
      // 获取目标元素的位置
      const targetRect = targetElement.getBoundingClientRect();
      const targetScrollTop = targetRect.top + window.scrollY - offset;

      // 使用平滑滚动
      container.scrollTo({
        top: targetScrollTop,
        behavior: 'smooth'
      });

      // 等待滚动完成
      setTimeout(() => {
        console.log('✅ 已滚动到目标位置');
        resolve(true);
      }, delay);
    } catch (error) {
      console.error('❌ 滚动过程出错:', error);
      reject(error);
    }
  });
} 